package org.jground.zk.zulX;

import org.jground.codetable.Codetable;
import org.jground.codetable.CodetableElement;
import org.jground.rx.RXLangStrings;
import org.jground.rx.RXPrincipalMethods;
import org.jground.rx.RXSystem;
import org.jground.zk.util.ZKUtils;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;

public class ComboboxX extends Combobox {

    private Codetable codetable;

    public ComboboxX(Codetable codetable) {
        setCodetable(codetable);
    }

    public void setCodetable(Codetable codetable) {
        RXPrincipalMethods pm =   RXSystem.getRXPrincipalMethods();
        ZKUtils.removeAllChildren(this);
        this.codetable = codetable;
        for (int i = 0; i < codetable.size(); i++) {
            CodetableElement cte = codetable.get(i);
            String name = RXLangStrings.getByPrincipalLang(cte.getNameLangStrings(), pm);
            Comboitem ci = new Comboitem(name);
            ci.setAttribute("code", cte);
            ci.setParent(this);
        }
    }

    public void setSelected(String code) {
        for (int i = 0; i < codetable.size(); i++) {
            CodetableElement cte = codetable.get(i);
            if (cte.getCode().equals(code)) {
                setSelectedIndex(i);
                return;
            }
        }
    }

    public String getSelected() {
        int index = getSelectedIndex();
        if (index == -1) {
            return null;
        }
        CodetableElement cte = codetable.get(index);
        if (Codetable.EMTPY_CODE_TABLE_ELEMENT.equals(cte)) {
            return null;
        } else {
            return cte.getCode();
        }
    }

}
